﻿using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System;

namespace MagicLib
{
    public class ToolsHotbox : EditorWindow
    {
        private enum HotboxRegion
        {
            None,
            CreateComponentCode,
            BatchRename,
        }

        // 热盒状态
        private Vector2 hotboxPosition;
        private HotboxRegion currentRegion;
        private Vector2 lastMousePosition;
        private float hotboxRadius = 120f;
        private float deadZoneRadius = 60f;

        // 静态标志：记录窗口是否已打开
        private static bool isWindowOpen = false;
        private static Vector2? initialWindowPosition = null;

        // 纹理
        private static Texture2D centerRingTexture;
        private static Texture2D directionArcTexture;
        private static Texture2D menuBackgroundNormalTexture;
        private static Texture2D menuBackgroundHighlightTexture;

        // 菜单项
        private List<HotboxRegion> regions = new List<HotboxRegion>();
        private Dictionary<HotboxRegion, HotboxMenuItem> regionMenuItems = new Dictionary<HotboxRegion, HotboxMenuItem>();

        // 修改点1：根据平台定义不同的菜单项快捷键
#if UNITY_EDITOR_WIN
        [MenuItem("MagicLib/ToolsHotbox &`", priority = 14)]
#else
        [MenuItem("MagicLib/ToolsHotbox %`", priority = 14)]
#endif
        public static void ShowWindow()
        {
            var window = GetWindow<ToolsHotbox>("ToolsHotbox");
            // 如果窗口已打开，只需聚焦它
            if (isWindowOpen)
            {
                window.Focus();
                return;
            }
            window.minSize = new Vector2(300, 300);

            // 如果已有初始位置，使用它（防止窗口移动）
            if (initialWindowPosition.HasValue)
            {
                window.position = new Rect(
                    initialWindowPosition.Value.x,
                    initialWindowPosition.Value.y,
                    window.minSize.x,
                    window.minSize.y
                );
            }
            else
            {
                // 首次打开：获取当前鼠标位置（屏幕坐标）
                Vector2 mousePosition = GUIUtility.GUIToScreenPoint(Event.current.mousePosition);

                // 设置窗口位置（使鼠标位于窗口中心）
                window.position = new Rect(
                    mousePosition.x - window.minSize.x / 2,
                    mousePosition.y - window.minSize.y / 2,
                    window.minSize.x,
                    window.minSize.y
                );

                // 记录初始位置
                initialWindowPosition = window.position.position;
            }

            // 标记窗口已打开
            isWindowOpen = true;
            window.Focus();
        }

        private void OnEnable()
        {
            CreateTextures();
            InitializeRegions();
            InitializeMenuItems();
        }

        private void OnDestroy()
        {
            // 窗口关闭时重置标志
            isWindowOpen = false;
            initialWindowPosition = null;
        }

        private void OnGUI()
        {
            // 确保热盒位置始终在窗口中心
            hotboxPosition = new Vector2(position.width / 2, position.height / 2);

            DrawHotbox();
            ProcessInput();
        }

        private void DrawHotbox()
        {
            // 绘制中心指示器
            DrawCenterIndicator();
            // 绘制区域标签
            DrawRegionLabels();
            // 绘制死区指示器
            DrawDeadZoneIndicator();
        }

        private void DrawCenterIndicator()
        {
            // 绘制中心圆环
            if (centerRingTexture != null)
            {
                Rect ringRect = new Rect(
                    hotboxPosition.x - deadZoneRadius,
                    hotboxPosition.y - deadZoneRadius,
                    deadZoneRadius * 2,
                    deadZoneRadius * 2
                );
                GUI.DrawTexture(ringRect, centerRingTexture, ScaleMode.ScaleToFit);
            }

            // 绘制方向扇形
            if (directionArcTexture != null)
            {
                // 计算鼠标方向角度
                Vector2 direction = lastMousePosition - hotboxPosition;
                float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

                // 保存当前GUI矩阵
                Matrix4x4 matrixBackup = GUI.matrix;

                // 围绕热盒中心旋转
                GUIUtility.RotateAroundPivot(angle, hotboxPosition);

                // 绘制扇形
                Rect arcRect = new Rect(
                    hotboxPosition.x - deadZoneRadius,
                    hotboxPosition.y - deadZoneRadius,
                    deadZoneRadius * 2,
                    deadZoneRadius * 2
                );
                GUI.DrawTexture(arcRect, directionArcTexture, ScaleMode.ScaleToFit);

                // 恢复GUI矩阵
                GUI.matrix = matrixBackup;
            }
        }

        private void DrawRegionLabels()
        {
            foreach (var region in regions)
            {
                if (region != HotboxRegion.None)
                {
                    DrawRegionLabel(region);
                }
            }
        }

        private void DrawRegionLabel(HotboxRegion region)
        {
            var menuItem = regionMenuItems[region];
            bool isHighlighted = region == currentRegion;
            Vector2 labelPos = hotboxPosition + menuItem.direction * hotboxRadius;

            // 使用图标背景
            Texture2D bgTexture = isHighlighted ? menuBackgroundHighlightTexture : menuBackgroundNormalTexture;

            // 标签大小
            float iconSize = 80f;
            Rect bgRect = new Rect(
                labelPos.x - iconSize / 2,
                labelPos.y - iconSize / 2,
                iconSize,
                iconSize
            );

            // 绘制背景图标
            if (bgTexture != null)
            {
                GUI.DrawTexture(bgRect, bgTexture, ScaleMode.ScaleToFit);
            }

            // 优化的标签样式
            GUIStyle labelStyle = new GUIStyle(EditorStyles.whiteLabel);
            labelStyle.normal.textColor = isHighlighted ? Color.white : Color.black;
            labelStyle.alignment = TextAnchor.MiddleCenter;
            labelStyle.fontSize = 11;
            labelStyle.fontStyle = FontStyle.Bold;
            labelStyle.padding = new RectOffset(0, 0, 0, 0);

            // 绘制文字
            GUI.Label(bgRect, menuItem.name, labelStyle);
        }

        private void DrawDeadZoneIndicator()
        {
            // 只保留文字提示
            GUIStyle labelStyle = new GUIStyle(EditorStyles.whiteLabel)
            {
                alignment = TextAnchor.MiddleCenter,
                fontSize = 10,
                normal = { textColor = new Color(0.8f, 0.8f, 0.8f, 0.7f) }
            };

            Rect labelRect = new Rect(
                hotboxPosition.x - 40,
                hotboxPosition.y - 10,
                80, 20
            );

            GUI.Label(labelRect, "MagicLib", labelStyle);
        }

        private void ProcessInput()
        {
            // 更新鼠标位置
            lastMousePosition = Event.current.mousePosition;

            // 更新当前区域
            UpdateCurrentRegion(lastMousePosition);

            // 检测快捷键松开事件
            Event e = Event.current;

            // 修改点2：根据平台检测不同的快捷键
            bool keyUpEvent = false;

#if UNITY_EDITOR_WIN
            // Windows: Alt + `
            keyUpEvent = e.type == EventType.KeyUp && e.keyCode == KeyCode.BackQuote;
#else
            // macOS: Cmd + `
            keyUpEvent = e.type == EventType.KeyUp && e.keyCode == KeyCode.BackQuote;
#endif

            if (keyUpEvent)
            {
                // 松开快捷键时执行当前区域的功能
                if (currentRegion != HotboxRegion.None)
                {
                    ExecuteRegionAction();
                }

                // 关闭窗口
                Close();
                e.Use();
            }

            // 强制重绘
            Repaint();
        }

        private void UpdateCurrentRegion(Vector2 mousePosition)
        {
            Vector2 direction = mousePosition - hotboxPosition;
            float distance = direction.magnitude;

            // 检查是否在死区内
            if (distance < deadZoneRadius)
            {
                currentRegion = HotboxRegion.None;
                return;
            }

            // 检查是否在热盒范围内
            if (distance > hotboxRadius * 5f)
            {
                currentRegion = HotboxRegion.None;
                return;
            }

            // 计算角度 (0-360度)
            float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
            angle = (angle + 360) % 360;

            // 精确区域划分
            if (angle >= 247.5f && angle < 292.5f)
                currentRegion = HotboxRegion.CreateComponentCode;
            else if (angle >= 67.5f && angle < 112.5f)
                currentRegion = HotboxRegion.BatchRename;
            else
                currentRegion = HotboxRegion.None;
        }

        private void ExecuteRegionAction()
        {
            if (currentRegion == HotboxRegion.None) return;

            if (regionMenuItems.TryGetValue(currentRegion, out var menuItem))
            {
                menuItem.action?.Invoke();
            }
        }

        private static void CreateTextures()
        {
            // 加载图标资源
            centerRingTexture = LoadTexture("CenterRing");
            directionArcTexture = LoadTexture("DirectionArc");
            menuBackgroundNormalTexture = LoadTexture("MenuBackgroundNormal");
            menuBackgroundHighlightTexture = LoadTexture("MenuBackgroundHighlight");

            // 如果没有加载到图标，创建备用纹理
            if (menuBackgroundNormalTexture == null)
            {
                menuBackgroundNormalTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
                menuBackgroundNormalTexture.SetPixel(0, 0, new Color(0.2f, 0.2f, 0.2f, 0.85f));
                menuBackgroundNormalTexture.Apply();
            }

            if (menuBackgroundHighlightTexture == null)
            {
                menuBackgroundHighlightTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
                menuBackgroundHighlightTexture.SetPixel(0, 0, new Color(0.1f, 0.4f, 0.8f, 0.95f));
                menuBackgroundHighlightTexture.Apply();
            }

            // macOS 特殊处理
            if (Application.platform == RuntimePlatform.OSXEditor)
            {
                if (centerRingTexture != null) centerRingTexture.hideFlags = HideFlags.HideAndDontSave;
                if (directionArcTexture != null) directionArcTexture.hideFlags = HideFlags.HideAndDontSave;
                if (menuBackgroundNormalTexture != null) menuBackgroundNormalTexture.hideFlags = HideFlags.HideAndDontSave;
                if (menuBackgroundHighlightTexture != null) menuBackgroundHighlightTexture.hideFlags = HideFlags.HideAndDontSave;
            }
        }

        private static Texture2D LoadTexture(string path)
        {
            return Resources.Load<Texture2D>(path);
        }

        private void InitializeRegions()
        {
            regions = new List<HotboxRegion>
            {
                HotboxRegion.CreateComponentCode,
                HotboxRegion.BatchRename,
            };
        }

        private void InitializeMenuItems()
        {
            // 北区域
            regionMenuItems[HotboxRegion.CreateComponentCode] = new HotboxMenuItem(
                "创建脚本",
                new Vector2(0, -1),
                () => CreateComponentCode.ToggleWindow()
            );

            // 南区域
            regionMenuItems[HotboxRegion.BatchRename] = new HotboxMenuItem(
                "批量重命名",
                new Vector2(0, 1),
                () => BatchRename.ToggleWindow()
            );
        }

        private class HotboxMenuItem
        {
            public string name;
            public Vector2 direction;
            public Action action;

            public HotboxMenuItem(string name, Vector2 direction, Action action)
            {
                this.name = name;
                this.direction = direction;
                this.action = action;
            }
        }
    }
}